<template>
    <div class="app-container">
        <el-form
            :model="queryParams"
            ref="queryRef"
            :inline="true"
            v-show="showSearch"
            label-width="68px"
        >
            <el-form-item label="套餐名称" prop="name">
                <el-input
                    v-model="queryParams.name"
                    placeholder="请输入套餐名称"
                    clearable
                    @keyup.enter="handleQuery"
                />
            </el-form-item>

            <el-form-item label="状态" prop="status">
                <el-select
                    v-model="queryParams.status"
                    placeholder="请选择状态"
                    style="width: 180px"
                    clearable
                >
                    <el-option
                        v-for="dict in product_status"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                    />
                </el-select>
            </el-form-item>

            <el-form-item label="热门套餐" prop="isPopular">
                <el-select
                    v-model="queryParams.isPopular"
                    placeholder="请选择是否热门"
                    style="width: 180px"
                    clearable
                >
                    <el-option label="全部" :value="null" />
                    <el-option label="是" :value="true" />
                    <el-option label="否" :value="false" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery"
                    >搜索</el-button
                >
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-card class="base-table" ref="fullTable">
            <TableSetup
                ref="tSetup"
                @onStripe="onStripe"
                @onRefresh="onRefresh"
                @onChange="onChange"
                @onfullTable="onfullTable"
                @onSearchChange="onSearchChange"
                :columns="columns"
                :isTable="isTable"
            >
                <template v-slot:operate>
                    <el-button
                        type="primary"
                        plain
                        icon="Plus"
                        @click="handleAdd"
                        v-hasPermi="['bg:product:add']"
                        >新增</el-button
                    >
                    <el-button
                        type="success"
                        plain
                        icon="Edit"
                        :disabled="single"
                        @click="handleUpdate"
                        v-hasPermi="['bg:product:edit']"
                        >修改</el-button
                    >
                    <el-button
                        type="danger"
                        plain
                        icon="Delete"
                        :disabled="multiple"
                        @click="handleDelete"
                        v-hasPermi="['bg:product:remove']"
                        >删除</el-button
                    >
                    <el-button
                        type="primary"
                        plain
                        icon="Upload"
                        @click="handleImport"
                        v-hasPermi="['bg:product:import']"
                        >导入</el-button
                    >
                    <el-button
                        type="warning"
                        plain
                        icon="Download"
                        @click="handleExport"
                        v-hasPermi="['bg:product:export']"
                        >导出</el-button
                    >
                </template>
            </TableSetup>
            <auto-table
                ref="multipleTable"
                class="mytable"
                :tableData="productList"
                :columns="columns"
                :loading="loading"
                :stripe="stripe"
                :tableHeight="tableHeight"
                @onColumnWidthChange="onColumnWidthChange"
                @onSelectionChange="handleSelectionChange"
            >
                <template #createTime="{ row }">
                    <span>{{ parseTime(row.createTime, '{y}-{m}-{d}') }}</span>
                </template>

                <template #month="{ row }">
                    <span>{{ row.month }}月</span>
                </template>

                <template #price="{ row }">
                    <span>¥{{ row.price / 100 }}</span>
                </template>

                <template #discount="{ row }">
                    <span v-if="row.discount">{{ row.discount }}%</span>
                    <span v-else>-</span>
                </template>
                <template #isPopular="{ row }">
                    <el-tag :type="row.isPopular ? 'danger' : 'info'">
                        {{ row.isPopular ? '热门' : '普通' }}
                    </el-tag>
                </template>
                <template #status="{ row }">
                    <dict-tag :options="product_status" :value="row.status" />
                </template>

                <template #prices="{ row }">
                    <el-tag
                        v-for="price in row.prices"
                        :key="price.id"
                        type="primary"
                        style="margin-left: 4px"
                        >{{ (price.randomPrice / 100).toFixed(2) }}</el-tag
                    >
                </template>

                <template #updateTime="{ row }">
                    <span>{{ parseTime(row.updateTime, '{y}-{m}-{d}') }}</span>
                </template>
                <template #operate="{ row }">
                    <el-button
                        link
                        type="success"
                        icon="Money"
                        @click="handlePriceManage(row)"
                        v-hasPermi="['bg:product:price:query']"
                        >价格管理</el-button
                    >
                    <el-button
                        link
                        type="primary"
                        icon="Edit"
                        @click="handleUpdate(row)"
                        v-hasPermi="['bg:product:edit']"
                        >修改</el-button
                    >

                    <el-button
                        link
                        type="primary"
                        icon="Delete"
                        @click="handleDelete(row)"
                        v-hasPermi="['bg:product:remove']"
                        >删除</el-button
                    >
                </template>
            </auto-table>
            <div class="table-pagination">
                <pagination
                    v-show="total > 0"
                    :total="total"
                    v-model:page="queryParams.pageNum"
                    v-model:limit="queryParams.pageSize"
                    @pagination="getList"
                />
            </div>
        </el-card>

        <!-- 添加或修改素材产品对话框 -->
        <el-dialog :title="title" v-model="open" width="800px" append-to-body>
            <el-form
                ref="productRef"
                :model="form"
                :rules="rules"
                label-width="120px"
            >
                <el-form-item label="套餐名称" prop="name">
                    <el-input
                        v-model="form.name"
                        placeholder="请输入套餐名称"
                    />
                </el-form-item>
                <el-form-item label="套餐周期(月)" prop="month">
                    <el-input
                        v-model="form.month"
                        placeholder="请输入套餐周期"
                    />
                </el-form-item>
                <el-form-item label="套餐类型" prop="tip">
                    <el-input v-model="form.tip" placeholder="请输入套餐类型" />
                </el-form-item>

                <el-form-item label="价格(分)" prop="price">
                    <el-input-number
                        v-model="form.price"
                        :min="0"
                        placeholder="请输入现价"
                    />
                </el-form-item>
                <el-form-item label="排序" prop="index">
                    <el-input v-model="form.index" placeholder="请输入排序" />
                </el-form-item>

                <el-form-item label="折扣%" prop="discount">
                    <el-input-number
                        v-model="form.discount"
                        :min="0"
                        :max="100"
                        placeholder="请输入折扣"
                    />
                </el-form-item>

                <el-form-item label="套餐描述" prop="description">
                    <el-input
                        v-model="form.description"
                        type="textarea"
                        :rows="3"
                        placeholder="请输入套餐描述"
                    />
                </el-form-item>

                <el-form-item label="最大下载次数" prop="maxDownloads">
                    <el-input-number
                        v-model="form.maxDownloads"
                        :min="-1"
                        placeholder="请输入最大下载次数"
                    />
                </el-form-item>

                <el-form-item label="是否热门" prop="isPopular">
                    <el-radio-group v-model="form.isPopular">
                        <el-radio :value="false">否</el-radio>
                        <el-radio :value="true">是</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="状态" prop="status">
                    <el-select v-model="form.status" placeholder="请选择状态">
                        <el-option
                            v-for="dict in product_status"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                        ></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm"
                        >确 定</el-button
                    >
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
        <!-- 导入数据对话框 -->
        <ImportData
            v-if="openImport"
            v-model="openImport"
            tableName="bg_product"
            @success="handleImportSuccess"
        />

        <!-- 价格管理对话框 -->
        <el-dialog
            title="价格管理"
            v-model="priceDialogOpen"
            width="1000px"
            append-to-body
        >
            <div class="price-management">
                <div class="price-header">
                    <h3>{{ currentProduct.name }} - 价格管理</h3>
                    <el-button
                        type="primary"
                        icon="Plus"
                        @click="handleAddPrice"
                        v-hasPermi="['bg:product:price:add']"
                    >
                        添加价格
                    </el-button>
                </div>

                <el-table
                    :data="priceList"
                    v-loading="priceLoading"
                    style="width: 100%"
                >
                    <el-table-column prop="id" label="ID" width="80" />
                    <el-table-column
                        prop="randomPrice"
                        label="实际价格"
                        width="120"
                    >
                        <template #default="{ row }">
                            <span
                                >¥{{ (row.randomPrice / 100).toFixed(2) }}</span
                            >
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="imageUrl"
                        label="支付二维码"
                        width="200"
                    >
                        <template #default="{ row }">
                            <el-image
                                v-if="row.imageUrl"
                                :src="row.imageUrl"
                                style="width: 100px; height: 100px"
                                fit="cover"
                                :preview-src-list="[row.imageUrl]"
                            />
                            <span v-else>未上传</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="createTime"
                        label="创建时间"
                        width="180"
                    >
                        <template #default="{ row }">
                            <span>{{
                                parseTime(
                                    row.createTime,
                                    '{y}-{m}-{d} {h}:{i}:{s}'
                                )
                            }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="150">
                        <template #default="{ row }">
                            <el-button
                                link
                                type="primary"
                                icon="Edit"
                                @click="handleEditPrice(row)"
                                v-hasPermi="['bg:product:price:edit']"
                            >
                                编辑
                            </el-button>
                            <el-button
                                link
                                type="danger"
                                icon="Delete"
                                @click="handleDeletePrice(row)"
                                v-hasPermi="['bg:product:price:remove']"
                            >
                                删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </el-dialog>

        <!-- 添加/编辑价格对话框 -->
        <el-dialog
            :title="priceForm.id ? '编辑价格' : '添加价格'"
            v-model="priceFormOpen"
            width="500px"
            append-to-body
        >
            <el-form
                ref="priceFormRef"
                :model="priceForm"
                :rules="priceRules"
                label-width="100px"
            >
                <el-form-item label="实际价格" prop="randomPrice">
                    <el-input-number
                        v-model="priceForm.randomPrice"
                        :min="0"
                        :precision="2"
                        placeholder="请输入实际价格"
                        style="width: 100%"
                    />
                    <div class="form-tip">单位：元</div>
                </el-form-item>

                <el-form-item label="支付二维码" prop="imageUrl">
                    <el-upload
                        class="upload-demo"
                        :action="uploadUrl"
                        :headers="uploadHeaders"
                        :on-success="handleUploadSuccess"
                        :before-upload="beforeUpload"
                        :show-file-list="false"
                        accept="image/*"
                    >
                        <el-button type="primary" icon="Upload"
                            >上传二维码</el-button
                        >
                    </el-upload>
                    <div v-if="priceForm.imageUrl" class="upload-preview">
                        <el-image
                            :src="priceForm.imageUrl"
                            style="
                                width: 200px;
                                height: 200px;
                                margin-top: 10px;
                            "
                            fit="cover"
                        />
                    </div>
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitPriceForm"
                        >确 定</el-button
                    >
                    <el-button @click="cancelPriceForm">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="BgProduct">
import {
    listProduct,
    getProduct,
    delProduct,
    addProduct,
    updateProduct,
    importProduct
} from '@/api/bg/product'
import {
    listProductPrice,
    getProductPrice,
    delProductPrice,
    addProductPrice,
    updateProductPrice
} from '@/api/bg/productPrice'
import { listAllTable } from '@/api/system/table'
import TableSetup from '@/components/TableSetup'
import AutoTable from '@/components/AutoTable'
import ImportData from '@/components/ImportData'
import { getToken } from '@/utils/auth'
const { proxy } = getCurrentInstance()
const { product_status } = proxy.useDict('product_status')

const productList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')

const columns = ref([])
const stripe = ref(true)
const isTable = ref(true)
const tableHeight = ref(500)
const fullScreen = ref(false)
const openImport = ref(false)

// 价格管理相关
const priceDialogOpen = ref(false)
const priceFormOpen = ref(false)
const priceLoading = ref(false)
const priceList = ref([])
const currentProduct = ref({})
const priceForm = ref({
    id: null,
    productId: null,
    randomPrice: null,
    imageUrl: null
})
const priceRules = ref({
    randomPrice: [
        { required: true, message: '实际价格不能为空', trigger: 'blur' }
    ]
})
const uploadUrl = ref(import.meta.env.VITE_APP_BASE_API + '/common/upload')
const uploadHeaders = ref({
    Authorization: 'Bearer ' + getToken()
})

const data = reactive({
    form: {},
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        status: null,
        isPopular: null
    },
    rules: {
        createBy: [
            { required: true, message: '创建者不能为空', trigger: 'blur' }
        ],
        deptId: [
            { required: true, message: '部门id不能为空', trigger: 'blur' }
        ],
        discount: [
            { required: true, message: '折扣%不能为空', trigger: 'blur' }
        ],
        index: [{ required: true, message: '排序不能为空', trigger: 'blur' }],
        month: [
            { required: true, message: '套餐周期不能为空', trigger: 'blur' }
        ],
        name: [
            { required: true, message: '套餐名称不能为空', trigger: 'blur' }
        ],
        price: [{ required: true, message: '价格不能为空', trigger: 'blur' }],
        status: [{ required: true, message: '状态不能为空', trigger: 'change' }]
    }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询素材产品列表 */
function getList() {
    loading.value = true
    listProduct(queryParams.value).then((response) => {
        productList.value = response.rows
        total.value = response.total
        loading.value = false
    })
}

function getColumns() {
    listAllTable({ tableName: 'bg_product' })
        .then((response) => {
            columns.value = response.data
        })
        .then(() => {
            getList()
        })
}

// 取消按钮
function cancel() {
    open.value = false
    reset()
}

// 表单重置
function reset() {
    form.value = {
        id: null,
        name: null,
        month: 1,
        tip: null,
        price: null,
        discount: 100,
        description: null,
        maxDownloads: -1,
        isPopular: false,
        index: 0,
        status: '1'
    }
    proxy.resetForm('productRef')
}

/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1
    getList()
}

/** 重置按钮操作 */
function resetQuery() {
    proxy.resetForm('queryRef')
    handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
    ids.value = selection.map((item) => item.id)
    single.value = selection.length != 1
    multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
    reset()
    open.value = true
    title.value = '添加素材产品'
}

/** 新增按钮操作 */
function handleImport() {
    openImport.value = true
}

/** 修改按钮操作 */
function handleUpdate(row) {
    reset()
    const bgProductId = row.id || ids.value
    getProduct(bgProductId).then((response) => {
        form.value = response.data
        open.value = true
        title.value = '修改素材产品'
    })
}

/** 提交按钮 */
function submitForm() {
    proxy.$refs['productRef'].validate((valid) => {
        if (valid) {
            if (form.value.id != null) {
                updateProduct(form.value).then((response) => {
                    proxy.$modal.msgSuccess('修改成功')
                    open.value = false
                    getList()
                })
            } else {
                addProduct(form.value).then((response) => {
                    proxy.$modal.msgSuccess('新增成功')
                    open.value = false
                    getList()
                })
            }
        }
    })
}

/** 删除按钮操作 */
function handleDelete(row) {
    const _ids = row.id || ids.value
    proxy.$modal
        .confirm('是否确认删除素材产品编号为"' + _ids + '"的数据项？')
        .then(function () {
            return delProduct(_ids)
        })
        .then(() => {
            getList()
            proxy.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
    proxy.download(
        'bg/product/export',
        {
            ...queryParams.value
        },
        `product_${new Date().getTime()}.xlsx`
    )
}

//表格全屏
function onfullTable() {
    proxy.$refs.tSetup.onFull(proxy.$refs.fullTable.$el)
    fullScreen.value = !fullScreen.value
    updateTableHeight()
}
//表格刷新
function onRefresh() {
    getList()
}
//搜索框显示隐藏
function onSearchChange() {
    showSearch.value = !showSearch.value
}

function onStripe(val) {
    stripe.value = val
}
//改变表头数据
function onChange(val) {
    columns.value = val
}

//改变表格宽度
function onColumnWidthChange(column) {
    proxy.$refs.tSetup.tableWidth(column)
}

//更新表格高度
function updateTableHeight() {
    if (
        proxy.$refs.tSetup &&
        proxy.$refs.queryRef &&
        document.querySelector('.table-pagination')
    ) {
        if (fullScreen.value) {
            tableHeight.value = window.innerHeight - 145
        } else {
            tableHeight.value =
                window.innerHeight -
                proxy.$refs.tSetup.$el.clientHeight -
                proxy.$refs.queryRef.$el.clientHeight -
                document.querySelector('.table-pagination').clientHeight -
                220
        }
    }
}
//导入成功
function handleImportSuccess(sheetName, filedInfo, fileName) {
    let data = {
        tableName: 'bg_product',
        filedInfo: filedInfo,
        fileName: fileName,
        sheetName: sheetName
    }
    importProduct(data).then(() => {
        proxy.$modal.msgSuccess('导入成功')
        openImport.value = false
        getList()
    })
    getList()
}

onMounted(() => {
    updateTableHeight() // 初始化计算高度
    window.addEventListener('resize', updateTableHeight) // 监听窗口大小变化
})

onUnmounted(() => {
    window.removeEventListener('resize', updateTableHeight) // 销毁监听
})

// 价格管理相关方法
/** 价格管理按钮操作 */
function handlePriceManage(row) {
    currentProduct.value = row
    priceDialogOpen.value = true
    getPriceList(row.id)
}

/** 获取价格列表 */
function getPriceList(productId) {
    priceLoading.value = true
    listProductPrice({ productId: productId })
        .then((response) => {
            console.log(response)
            priceList.value = response.rows || response.data || []
            priceLoading.value = false
        })
        .catch(() => {
            priceLoading.value = false
        })
}

/** 添加价格按钮操作 */
function handleAddPrice() {
    resetPriceForm()
    priceForm.value.productId = currentProduct.value.id
    priceFormOpen.value = true
}

/** 编辑价格按钮操作 */
function handleEditPrice(row) {
    resetPriceForm()
    priceForm.value = {
        id: row.id,
        productId: row.productId,
        randomPrice: row.randomPrice / 100, // 转换为元
        imageUrl: row.imageUrl
    }
    priceFormOpen.value = true
}

/** 删除价格按钮操作 */
function handleDeletePrice(row) {
    proxy.$modal
        .confirm('是否确认删除该价格记录？')
        .then(function () {
            return delProductPrice(row.id)
        })
        .then(() => {
            getPriceList(currentProduct.value.id)
            proxy.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
}

/** 提交价格表单 */
function submitPriceForm() {
    proxy.$refs['priceFormRef'].validate((valid) => {
        if (valid) {
            const formData = {
                ...priceForm.value,
                randomPrice: Math.round(priceForm.value.randomPrice * 100) // 转换为分
            }

            if (formData.id != null) {
                updateProductPrice(formData).then((response) => {
                    proxy.$modal.msgSuccess('修改成功')
                    priceFormOpen.value = false
                    getPriceList(currentProduct.value.id)
                })
            } else {
                addProductPrice(formData).then((response) => {
                    proxy.$modal.msgSuccess('新增成功')
                    priceFormOpen.value = false
                    getPriceList(currentProduct.value.id)
                })
            }
        }
    })
}

/** 取消价格表单 */
function cancelPriceForm() {
    priceFormOpen.value = false
    resetPriceForm()
}

/** 重置价格表单 */
function resetPriceForm() {
    priceForm.value = {
        id: null,
        productId: null,
        randomPrice: null,
        imageUrl: null
    }
    proxy.resetForm('priceFormRef')
}

/** 文件上传成功回调 */
function handleUploadSuccess(response) {
    if (response.code === 200) {
        priceForm.value.imageUrl = response.url
        proxy.$modal.msgSuccess('上传成功')
    } else {
        proxy.$modal.msgError(response.msg || '上传失败')
    }
}

/** 文件上传前校验 */
function beforeUpload(file) {
    const isImage = file.type.startsWith('image/')
    const isLt2M = file.size / 1024 / 1024 < 2

    if (!isImage) {
        proxy.$modal.msgError('只能上传图片文件!')
        return false
    }
    if (!isLt2M) {
        proxy.$modal.msgError('上传图片大小不能超过 2MB!')
        return false
    }
    return true
}

getColumns()
</script>

<style scoped>
.price-management {
    padding: 20px 0;
}

.price-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #ebeef5;
}

.price-header h3 {
    margin: 0;
    color: #303133;
    font-size: 18px;
    font-weight: 600;
}

.form-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 5px;
}

.upload-preview {
    margin-top: 10px;
}

.upload-demo {
    width: 100%;
}
</style>